<?php
/**
 * 会员逻辑层
 * @author maniac
 */
namespace app\common\logic;

use app\common\model\MemberRoles;
use app\common\model\Fields;
use app\common\model\MemberData;
use app\common\service\PointsService;
use function Symfony\Component\String\u;

class Members extends Base
{

    
    /**
     * 重组提交信息
     * @param  array $data 请求的信息
     */
    public function recombine($data)
    {
        if (empty($data['username'])){
            exception("请输入会员姓名");
        }
        if (empty($data['mobile'])){
            exception("请输入手机号");
        }
        if (empty($data['birthday'])){
            exception("请输入会员生日");
        }

        if ((float)$data['points'] == false){
            exception("请输入会员积分");
        }
        $member = \app\common\model\Members::where("mobile",$data['mobile'])->where("create_type",1)->value('id');
        if (!empty($member)){
            exception("录入手机号重复");
        }
        return $data;
    }
    public function save($data)
    {
        $points = $data['points'];
        unset($data['points']);
        $data['status'] = 1;
        $data['checked'] = 1;
        $data['create_type'] = 1;
        $member = \app\common\model\Members::where("mobile",$data['mobile'])->where("create_type",0)->find();
        if (empty($member)){
            $member_id = parent::save($data);
        }else{
            //绑定用户
//            if (!$member['is_binding']){
                \app\common\model\Members::where("id",$member['id'])->update([
                    'username' => $data['username'],
                    'birthday' => $data['birthday'],
                    'is_binding' => 1,
                ]);
//            }
            $member_id =  $member['id'];
        }
        //获取当前管理员
        $userid     = session('userid', '', session_prefix());
        //获取管理员类型
        $type = \app\common\model\Users::where("id",$userid)->value('type');
        $status = $type != 2 ? 1 : 0;
        //获取门店id
        $stores_id = \app\common\model\Users::where("id",$userid)->value('stores_id');
        //修改门店id
        \app\common\model\Members::where("id",$member_id)->update([
            'stores_id' => $stores_id,
        ]);
        //添加积分记录
        (new PointsService())->SaveMemberPoints($member_id,$points,$status,$userid,0,"后台操作积分");
        if($status){
            //重算积分
            (new PointsService())->RecalculationMemberPoints($member_id);
            //重算总积分
            (new PointsService())->RecalculationMemberTotalPoints($member_id);
            //重置会员角色等级
            (new PointsService())->ResetMemberRole($member_id);
        }
        return true;
    }

}
